package com.xiaojianone.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaojianone.utils.JwtHelper;
import com.xiaojianone.utils.Result;
import com.xiaojianone.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName  LoginProtectedInterceptor
 * Author  XiaojianOne
 * Date  2025/2/18 22:41
 * Version  8.0
 */

@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        boolean expiration = jwtHelper.isExpiration(token);

        if (! expiration){
            return true;
        }

        //无效返回504的状态json
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().print(json);

        return false;
    }
}
